package com.lhq.business.controller;

import cn.hutool.core.bean.BeanUtil;
import com.lhq.business.domain.Book;
import com.lhq.business.entity.BookShelf;
import com.lhq.business.entity.ReadBook;
import com.lhq.business.repo.BookShelfRepository;
import com.lhq.business.service.IBookService;
import com.lhq.business.service.IChapterService;
import com.lhq.common.annotation.Anonymous;
import com.lhq.common.core.controller.BaseController;
import com.lhq.common.core.domain.AjaxResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;
import java.util.Optional;

/**
 * 书架相关请求
 * @author lhq
 * @version 1.0
 * @date 2024/7/23 10:37
 */
@RestController
@RequestMapping("/business/bookshelf")
public class BookShelfController extends BaseController {
    @Autowired
    private IBookService bookService;
    @Autowired
    private BookShelfRepository  bookShelfRepository;
    @Autowired
    private IChapterService chapterService;
    /**
     *  获取书架图书
     *
     * @author lhq
     * @date 2024/7/23 10:38
     * @version 1.0
     */
    @Anonymous
    @GetMapping("/list/{uid}")
    public AjaxResult getBooks(@PathVariable("uid") String uid ){
        BookShelf bookShelf = new BookShelf();
        bookShelf.setUid("1");
        Optional<BookShelf> shelf = bookShelfRepository.findAllByUserId(uid);
        if(shelf.isPresent()) {
            List<ReadBook> books =  shelf.get().getShelf();
            books.forEach(book -> {
                Book bookInfo = bookService.selectById(book.getId());
                if (bookInfo != null) {
                    BeanUtil.copyProperties(bookInfo, book);
                    book.setChapterCnt(chapterService.selectCountByBookId(book.getId()));
                }
            });
        }else {
            throw new RuntimeException("书架不存在");
        }
        return success(shelf);
    }
}
